package com.mantru.iotpot.Adapter

import android.annotation.SuppressLint
import android.app.AlertDialog
import android.content.Context
import android.text.Editable
import android.text.TextWatcher
import android.view.KeyEvent
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity.INPUT_METHOD_SERVICE
import com.mantru.iotpot.Adapter.Base.AppAdapter
import com.mantru.iotpot.Adapter.Base.AppHolder
import com.mantru.iotpot.Bean.DishesCreateSauceBean
import com.mantru.iotpot.R
import com.mantru.iotpot.modbus.Common
import androidx.core.graphics.toColorInt
import com.mantru.iotpot.Util.MathUtil
import com.mantru.iotpot.Util.ToastUtils

class DishesCreateSauceAdapter(var context: Context, layoutResId: Int, var data: List<DishesCreateSauceBean>, var dishesCreateSauceNameList: MutableList<String>): AppAdapter<DishesCreateSauceBean>(context, layoutResId, data) {

    private var dishesCreateSauceListener: DishesCreateSauceListener? = null
    fun setDishesCreateSauceListener(dishesCreateSauceListener: DishesCreateSauceListener?) {
        this.dishesCreateSauceListener = dishesCreateSauceListener
    }
    interface DishesCreateSauceListener {
        fun onDelete(listPosition: Int)
        fun setName(listPosition: Int, value: String)
        fun setValue(listPosition: Int, value: String)
    }
    
    override fun convert(holder: AppHolder?, position: Int, item: DishesCreateSauceBean) {
        try {
            holder?.setOnClickListener(R.id.adapter_dishes_create_sauce_value_delete){//监听删除按钮
                dishesCreateSauceListener?.onDelete(position)
            }
                ?.setVisibility(R.id.adapter_dishes_create_sauce_value_delete,position != 0)
                ?.setOnClickListener(R.id.adapter_dishes_create_sauce_name){//设置调味料名弹窗弹出点击事件
                    showPortionDialog(position, holder)
                }
                ?.setText(R.id.adapter_dishes_create_sauce_name_textview, item.name)
                ?.setText(R.id.adapter_dishes_create_sauce_value_edittext, item.value)
            val weight = holder?.getView<EditText>(R.id.adapter_dishes_create_sauce_value_edittext)

            weight!!.addTextChangedListener(object : TextWatcher {
                override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

                override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                    //这里要新增逻辑，如果输入了0开头，而非0的数据，要把开头的0去掉
                    dishesCreateSauceListener?.setValue(holder.layoutPosition, MathUtil.trimLeadingZeros(s.toString()))
                }

                override fun afterTextChanged(s: Editable?) {}
            })

            weight.setOnEditorActionListener { v: TextView, actionId: Int, event: KeyEvent? ->
                // 检查是否是按下 Enter 键或者完成操作
                if ((event != null && event.action == KeyEvent.ACTION_DOWN && event.keyCode == KeyEvent.KEYCODE_ENTER)
                    || actionId == android.view.inputmethod.EditorInfo.IME_ACTION_DONE
                    || actionId == android.view.inputmethod.EditorInfo.IME_ACTION_NEXT
                    || actionId == android.view.inputmethod.EditorInfo.IME_ACTION_SEND) {

                    // 获取输入法管理器
                    val imm = context.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager?
                    // 隐藏软键盘
                    imm?.hideSoftInputFromWindow(v.windowToken, 0)
                    // 让输入框失去焦点
                    v.clearFocus()
                    return@setOnEditorActionListener true
                }
                return@setOnEditorActionListener false
            }

        } catch (e: Exception){
            e.toString()
        }
    }


    @SuppressLint("SetTextI18n")
    //弹出份数弹窗
    private fun showPortionDialog(position: Int, holder: AppHolder?) {
        val builder: AlertDialog.Builder = AlertDialog.Builder(context)
        builder.setTitle("选择调味料")

        val portions = Common.nozzle_name_list
            .toList()
            .subList(1, Common.nozzle_name_list.size)
            .filter { it != "洗锅水" } // 过滤掉“洗锅水”
            .toTypedArray()

        builder.setItems(portions) { _, which ->
            val selected: Int = which // 获取选中的调味料
            if ( dishesCreateSauceNameList.contains(portions[selected]) ){
                //Toast.makeText(context, "已经选择过" + portions[selected] +"，请选择其他材料", Toast.LENGTH_SHORT).show()
                ToastUtils.show(context, "已经选择过" + portions[selected] +"，请选择其他材料")
                return@setItems
            }
            holder?.setText(R.id.adapter_dishes_create_sauce_name_textview, portions[selected])
            holder?.setTextColor(R.id.adapter_dishes_create_sauce_name_textview,
                "#FFFFFF".toColorInt())
            dishesCreateSauceListener?.setName(position, portions[selected])
        }

        builder.show()
    }
}